import React, { Component } from 'react';
import { connect } from 'dva';
// import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {Divider, Form, Row, Col, Table, Button, message, Input, Cascader, Upload, Modal, Icon,} from 'antd';
import router from 'umi/router';
// import Login from '@/components/Login';
import styles from './OrderLook.less';
import area from "../../assets/area";
import Ellipsis from '@/components/Ellipsis';
import cookie from "react-cookies";

const FormItem = Form.Item;
const { TextArea } = Input;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

@Form.create()
@connect(({ orderLook, loading }) => ({
  orderLook,
  loading: loading.models.order,
}))
class OrderLookPage extends Component {
  constructor(props){
    super(props);
    this.state = {
      type: 'account',
      id: null,
      status: null,
      type: null,
      previewVisible: false,
      previewImage: '',
      fileList: [
        // {
        //   uid: '-1',
        //   name: 'xxx.png',
        //   status: 'done',
        //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        // },
      ],
    };
  }

  componentDidMount() {
    const { dispatch,history} = this.props;
    if (history && history.location) {
      const { state } = history.location;
      if(state){
        this.setState({
          id: state.id,
          status: state.status,
          type: state.type,
        });
        dispatch({
          type: 'orderLook/fetchDetail',
          payload: {
            orderHeadId: state.id,
          },
        }).then(()=> {
          const {orderLook: { pageInfoDetail }} = this.props;
          const {fileList} = this.state;
          if(pageInfoDetail && pageInfoDetail.fileUrl) {
            const obj={
              uid:1,
              url:pageInfoDetail.fileUrl,
            }
            fileList.push(obj);
            this.setState({
              fileList,
            })
          }
        });
      }
    }
  }

  onTabChange = type => {
    this.setState({ type });
  };

  handleSubmit = (err, values) => {
    const { type } = this.state;
    if (!err) {
      const { dispatch } = this.props;
      dispatch({
        type: 'login/login',
        payload: {
          ...values,
          type,
        },
      });
    }
  };

  handleToBack = () => {
    const pathname = '/demo/orderlist';
    router.push({
      pathname,
    });
  };

  handleSureGoods = () => {
    const { dispatch, orderLook: { pageInfoDetail } } = this.props;
    const { id,status } = this.state;
    const params = {
      id,
      status:status==='PAYED'? 'SHIPPED':status==='SHIPPED'?'SIGNED':null,
      rowVersion: pageInfoDetail && pageInfoDetail.rowVersion,
    };
    dispatch({
      type: 'orderLook/handleDeliverGoods',
      payload: {
        ...params,
      },
    }).then(() => {
      const { orderLook: { code } } = this.props;
      if (code.result) {
        message.success('成功');
        this.props.history.push({
          pathname:'/demo/orderList',
        })
      }
    });
  };

  handlePay = () => {
    const { form,dispatch,orderLook:{pageInfoDetail} } = this.props;
    const { id,fileList } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      const params = {
        ...values,
        id,
        status:'PAYED',
        rowVersion: pageInfoDetail && pageInfoDetail.rowVersion,
        receiveProvice:values.receiveProvice.length>0 && values.receiveProvice[0] || null,
        receiveCity:values.receiveProvice.length>0 && values.receiveProvice[1] || null,
        receiveDistrict:values.receiveProvice.length>0 && values.receiveProvice[2] || null,
        fileUrl:fileList[0].response.result,
      };
      dispatch({
        type: 'orderLook/handleDeliverGoods',
        payload: {
          ...params,
        },
      }).then(() => {
        const { orderLook: { code } } = this.props;
        if (code.result) {
          if(params.status === "PAYED"){
            router.push('/demo/success');
          }else{
            message.success('成功');
          }
        }
      });
    });
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = info =>{
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    this.setState({ fileList });
  }

  render() {
    const { orderLook: { pageInfoDetail },form: { getFieldDecorator },loading } = this.props;
    const { status,type } = this.state;
    const { id } = this.state;
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
        md: { span: 16 },
      },
    };
    const columns = [
      {
        title: '图片',
        dataIndex: 'imgUrl',
        width:100,
        render:text => <img className={styles.tableImg} src={text} />
      },
      {
        title: '商品名称',
        dataIndex: 'commodityName',
        width:400,
        render:(text,record) => (
          <div>
            <p style={{color:'#000',fontWeight:'bold'}}>{record.commodityName}</p>
            <Ellipsis lines={1} length={20}>{record.commodityCategoryName}</Ellipsis>
          </div>
          )
      },
      {
        title: '价格',
        dataIndex: 'unitPrice',
        render:text => (
          <div>
            价格：{text || ''}元
          </div>
        )
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        render:text => (
          <div>
            数量：{text || ''}个
          </div>
        )
      },
      {
        title: '总金额',
        dataIndex: 'amount',
        render:text => (
          <div>
            总金额：{text || ''}元
          </div>
        )
      },
    ];
    return (
      <div className={styles.main}>
        <Divider>地址信息</Divider>
        <div className={styles.address}>
          <div>
            {
              status && (status!=='CREATED' || type===1) &&
              <Form className={styles.reductionFrom}>
                <Row>
                  <Col span={12}>
                    <FormItem
                      label='收件人'
                      {...formItemLayout}
                    >
                      {(<span>{pageInfoDetail && pageInfoDetail.receiveContactName}</span>)}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem
                      label='联系电话'
                      {...formItemLayout}
                    >
                      {(<span>{pageInfoDetail && pageInfoDetail.receiveContactMobile}</span>)}
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <FormItem
                      label='地址'
                      {...formItemLayout}
                    >
                      {(<span>{`${pageInfoDetail && pageInfoDetail.receiveProvice || ''}${pageInfoDetail && pageInfoDetail.receiveCity || ''}${pageInfoDetail && pageInfoDetail.receiveDistrict || ''}`}</span>)}
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <FormItem
                      label='详细地址'
                      {...formItemLayout}
                    >
                      {(<span>{pageInfoDetail && pageInfoDetail.receiveAddress}</span>)}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem
                      label='上传图片'
                      {...formItemLayout}
                    >
                      <div className="clearfix">
                        <Upload
                          action="/api82/order/orderHead/upload"
                          listType="picture-card"
                          fileList={fileList}
                          data={{id:id}}
                          headers={
                            {authorization:"bearer " + (cookie.load("access_token")?cookie.load("access_token"):'')}
                          }
                          onPreview={this.handlePreview}
                          onRemove={false}
                          onChange={this.handleChange}
                        >
                          {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                          <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                      </div>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            }
            {
              status && status==='CREATED' && type!==1 &&
              <Form className={styles.reductionFrom}>
                <Row>
                  <Col span={12}>
                    <FormItem
                      label='收件人'
                      {...formItemLayout}
                    >
                      {getFieldDecorator('receiveContactName',{
                        initialValue:pageInfoDetail && pageInfoDetail.receiveContactName,
                        rules: [
                          {
                            required: true,
                            message: "请输入",
                          },
                        ],
                      })(<Input placeholder='请输入' />)}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem
                      label='联系电话'
                      {...formItemLayout}
                    >
                      {getFieldDecorator('receiveContactMobile',{
                        initialValue:pageInfoDetail && pageInfoDetail.receiveContactMobile,
                        rules: [
                          {
                            required: true,
                            message: "请输入",
                          },
                          { pattern: /^1(3|4|5|7|8)\d{9}$/, message: '请输入正确的手机号' },
                        ],
                      })(<Input placeholder='请输入' />)}
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <FormItem
                      label='地址'
                      {...formItemLayout}
                    >
                      {getFieldDecorator('receiveProvice',{
                        initialValue:pageInfoDetail && pageInfoDetail.receiveProvice && [pageInfoDetail && pageInfoDetail.receiveProvice,pageInfoDetail && pageInfoDetail.receiveCity,pageInfoDetail && pageInfoDetail.receiveDistrict] || [],
                        // initialValue:pageInfoDetail && pageInfoDetail.receiveProvice && [pageInfoDetail && pageInfoDetail.receiveProvice,pageInfoDetail && pageInfoDetail.receiveCity,pageInfoDetail && pageInfoDetail.receiveDistrict] || ['江苏省','苏州市','吴中区'],
                        rules: [
                          {
                            required: true,
                            message: "请选择",
                          },
                        ],
                      })(<Cascader
                        // defaultValue={pageInfoDetail && pageInfoDetail.receiveProvice && [pageInfoDetail && pageInfoDetail.receiveProvice,pageInfoDetail && pageInfoDetail.receiveCity,pageInfoDetail && pageInfoDetail.receiveDistrict] || []}
                        fieldNames={{ label: 'label', value: 'label', children: 'children' }}
                        options={area}
                        onChange={this.handleAddress}
                        placeholder="请选择"
                      />)}
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <FormItem
                      label='详细地址'
                      {...formItemLayout}
                    >
                      {getFieldDecorator('receiveAddress',{
                        initialValue:pageInfoDetail && pageInfoDetail.receiveAddress,
                        rules: [
                          {
                            required: true,
                            message: "请输入",
                          },
                        ],
                      })(<TextArea placeholder='请输入详细地址' rows={4} />)}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem
                      label='上传图片'
                      {...formItemLayout}
                    >
                      {getFieldDecorator('file',{
                        rules: [
                          {
                            required: false,
                          },
                        ],
                      })(
                        <div className="clearfix">
                          <Upload
                            action="/api82/order/orderHead/upload"
                            listType="picture-card"
                            fileList={fileList}
                            data={{id:id}}
                            headers={
                              {authorization:"bearer " + (cookie.load("access_token")?cookie.load("access_token"):'')}
                            }
                            onPreview={this.handlePreview}
                            onRemove={false}
                            onChange={this.handleChange}
                          >
                            {fileList.length >= 1 ? null : uploadButton}
                          </Upload>
                          <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                          </Modal>
                        </div>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            }
          </div>
        </div>
        <Divider>商品信息</Divider>
        <div>
          <Table
            loading={false}
            showHeader={false}
            columns={columns}
            rowKey={record => record.id}
            dataSource={pageInfoDetail && pageInfoDetail.orderLineVOList}
            pagination={false}
          />
        </div>
        <Row style={{ textAlign: 'right', marginTop: '20px',paddingRight:'10px' }}>
          {
            pageInfoDetail && pageInfoDetail.totalAmount &&
            <Col span={24}>
              订单金额
            </Col>
          }
          {
            pageInfoDetail && pageInfoDetail.totalAmount &&
            <Col span={24} style={{ color: 'black', fontSize: '20px' }}>
              {`￥ ${pageInfoDetail.totalAmount}`}
            </Col>
          }
          {
            type===1 &&
            <Col span={24} style={{ textAlign: 'right', marginTop: '20px' }}>
              <Button type="primary" onClick={this.handleToBack}>返回</Button>
            </Col>
          }
          {
            status && status!=='CREATED' && type!==1 &&
            <Col span={24} style={{ textAlign: 'right', marginTop: '20px' }}>
              {
                status!=='SIGNED' && <Button loading={loading} type="primary" style={{ marginRight: '20px' }} onClick={this.handleSureGoods}>{ status==='PAYED'?'确认发货':status==='SHIPPED'?'确认收货':'' }</Button>
              }
              <Button type="primary" onClick={this.handleToBack}>返回</Button>
            </Col>
          }
          {
            status && status==='CREATED' && type!==1 &&
            <Col span={24} style={{ textAlign: 'right', marginTop: '20px' }}>
              <Button style={{ marginRight: '20px' }} onClick={this.handleToBack}>取消</Button>
              <Button type="primary" loading={loading} onClick={this.handlePay}>支付订单</Button>
            </Col>
          }
        </Row>
      </div>
    );
  }
}

export default OrderLookPage;
